// pages/myclass/list/index.js
const App = getApp()
const db = wx.cloud.database()
const _ = db.command
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    Myclass: [],
    addMyclass: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this
    // 获取用户信息
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      UserInfo
    })
    that.getMyclass()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    that.getMyclass()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 切换tabs
  onChange(event) {
    console.log('切换到标签', event.detail.name);
    if (event.detail.name === 1) {
      that.getaddMyclass()
    }

  },
  // 我的加入
  getMyclass() {
    App.toast.showLoading('加载中...')
    db.collection('myclass').where({
        list: _.elemMatch({
          account: _.eq(that.data.UserInfo.account)
        })
      })
      .get({
        success: function (res) {
          let list = res.data
          for (let i = 0; i < list.length; i++) {
            list[i].path = '/pages/discussion/index'
            list[i].chatType = "class"
            list[i].chatId = 'chat' + list[i].myclassId
            list[i].chatName = list[i].name
            list[i].prompt = list[i].AdministratorName
          }
          console.log('我加入的班级', list)
          that.setData({
            Myclass: list
          })
          App.toast.hideLoading()
        }
      })
  },
  // 我的创建
  getaddMyclass() {
    App.toast.showLoading('加载中...')
    db.collection('myclass').where(_.or([{
          Administrator: that.data.UserInfo.account
        },
        {
          permissions: _.eq(that.data.UserInfo.permissions)
        }
      ]))
      .get({
        success: function (res) {
          console.log('我创建的班级', res.data)
          let list = res.data
          for (let i = 0; i < list.length; i++) {
            list[i].path = '/pages/discussion/index'
            list[i].chatType = "class"
            list[i].chatId = 'chat' + list[i].myclassId
            list[i].chatName = list[i].name
            list[i].prompt = list[i].AdministratorName
          }
          that.setData({
            addMyclass: list
          })
          App.toast.hideLoading()
        }
      })

  },
  // 创建班级
  Create() {
    App.route.navTo('/pages/myclass/add/index')
  },
  // 绑定班级
  binding() {
    App.route.navTo('/pages/myclass/binding/index')
  }
})